package com.zr.andealib.util;

import com.rfid.api.ADReaderInterface;
import com.rfid.api.GFunction;
import com.rfid.api.ISO15693Interface;
import com.rfid.api.ISO15693Tag;
import com.rfid.def.ApiErrDefinition;
import com.rfid.def.RfidDef;
import com.zr.andealib.util.constant.AndeaConstant;
import com.zr.andealib.util.constant.CheckUtil;
import com.zr.andealib.util.model.InventoryReport;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 * @author EnzoChan
 * @create 2019/3/18
 * @desc:
 */
public class CheckBookMediumUtil  implements CheckUtil {
    public ADReaderInterface mReader;
    public ADReaderInterface mReader1;
    private String conStrPara = "";
    private List<InventoryReport> inventoryList;

    private boolean initSuccess = true;

    public void init() {

        if (mReader == null) {
            mReader = new ADReaderInterface();
        }
        if (mReader1 == null) {
            mReader1 = new ADReaderInterface();
        }
        if (inventoryList == null || inventoryList.size() == 0) {
            inventoryList = new ArrayList<>();
        }
        OpenDev();
    }

    public List<String> bookGridIdInventory(int boxnum) {

        try {
            int caseNum;
            if (boxnum > 0 && boxnum <= 8) {
                caseNum = 1;
            } else {
                caseNum = 2;
                boxnum = boxnum - 8;
            }
            List<String> ret = __bookGridIdInventory(caseNum, boxnum);
            return ret;
        } catch (Exception e) {

        }
        return new ArrayList<>();
    }

    private List<String> __bookGridIdInventory(int caseNum, int boxnum) {
        List<String> boxsInventoryList = new ArrayList<String>();
        byte useAnt[] = {1, 2, 3, 4, 5, 6, 7, 8};
        if (boxnum > 0) {
            useAnt = new byte[1];
            useAnt[0] = (byte) boxnum;
        }
        if (inventoryTags(caseNum, useAnt)) {
            for (int i = 0; i < inventoryList.size(); i++)
                boxsInventoryList.add(inventoryList.get(i).getUidStr());
        }
        return boxsInventoryList;
    }

    private boolean inventoryTags(int caseno, byte useAnt[]) {


        ADReaderInterface reader;
        if (caseno == 1) {
            reader = mReader;
        } else {
            reader = mReader1;
        }

        if (reader == null) {
            // appendRunLog(new DebugInfo().line(), "rfid init failed");
//            return ErrorCode.E_READER_NULL;
            return false;
        } else if (!reader.isReaderOpen()) {
            return false;
        }
        byte newAI = RfidDef.AI_TYPE_NEW;
        Object hInvenParamSpecList = ADReaderInterface
                .RDR_CreateInvenParamSpecList();
        ISO15693Interface.ISO15693_CreateInvenParam(hInvenParamSpecList,
                (byte) 0, false, (byte) 0x00, (byte) 0);
        Vector<ISO15693Tag> tagsList = new Vector<>();
        long t1 = System.currentTimeMillis();
        int iret = reader.RDR_TagInventory(newAI, useAnt, 0,
                hInvenParamSpecList);
        if (iret == ApiErrDefinition.NO_ERROR) {
            //Close RF if inventory is successful.
            reader.RDR_CloseRFTransmitter();
        }
        long t2 = System.currentTimeMillis();
        int inventory_time_consuming = (int) (t2 - t1);
        System.out.println("时间差----->  " + inventory_time_consuming);
        if (iret == ApiErrDefinition.NO_ERROR) {
            Object tagReport = reader
                    .RDR_GetTagDataReport(RfidDef.RFID_SEEK_FIRST);
            while (tagReport != null) {
                ISO15693Tag tag = new ISO15693Tag();
                iret = ISO15693Interface.ISO15693_ParseTagDataReport(
                        tagReport, tag);
                if (iret == ApiErrDefinition.NO_ERROR) {
                    tagsList.add(tag);
                }

                tagReport = reader
                        .RDR_GetTagDataReport(RfidDef.RFID_SEEK_NEXT);
            }
            inventoryList.clear();
            for (ISO15693Tag t : tagsList) {
                boolean bTagExist = false;
                String uidStr = GFunction.encodeHexStr(t.uid);
                InventoryReport report = new InventoryReport(uidStr, "" + (int) t.ant_id);
                report.setBoxNum(useAnt[0]);

                for (InventoryReport tag : inventoryList) {
                    if (tag.getUidStr().equals(uidStr)) {
                        bTagExist = true;
                        break;
                    }
                }
                if (!bTagExist) {
                    inventoryList.add(report);
                }
            }
            if (useAnt.length == 1) {
                EventBus.getDefault().post(new HardEvent(inventoryList, AndeaConstant.CALL_READ_CHECK_SUCCSES));
            }
            return true;
        } else {
//            appendRunLog(new DebugInfo().line(), "inventoryTags error return: " + iret);
            EventBus.getDefault().post(new HardEvent( "盘点模块读取失败，请联系厂家解决", AndeaConstant.CALL_READ_CHECK_ERROR));
        }
        return false;
    }

    private void OpenDev() {
        String devName = "RD5100";
        conStrPara = String
                .format("RDType=%s;CommType=NET;RemoteIp=%s;RemotePort=9909", devName, "192.168.10.4");
        if (mReader.RDR_Open(conStrPara) != ApiErrDefinition.NO_ERROR) {
            initSuccess = false;
            EventBus.getDefault().post(new HardEvent( "柜体1初始化盘点模块失败，请联系厂家解决", AndeaConstant.CALL_INIT_CHECK_ERROR));
        }
        conStrPara = String
                .format("RDType=%s;CommType=NET;RemoteIp=%s;RemotePort=9909", devName, "192.168.10.5");
        if (mReader1.RDR_Open(conStrPara) != ApiErrDefinition.NO_ERROR) {
            initSuccess = false;
            EventBus.getDefault().post(new HardEvent( "柜体2初始化盘点模块失败，请联系厂家解决", AndeaConstant.CALL_INIT_CHECK_ERROR));
        }
    }

    public void destory() {
        if (mReader != null && initSuccess) {
            if (mReader.isReaderOpen()) {
                mReader.RDR_CloseRFTransmitter();
                mReader.RDR_SetCommuImmeTimeout();
                mReader.RDR_Close();
            }

        }
    }
}
